package com.codef.sharp.common.core.handler;

import com.codef.sharp.common.core.enums.ResponseStatus;
import com.codef.sharp.common.core.exception.SharpException;
import com.codef.sharp.common.core.response.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 统一异常处理
 * @author zhanrf
 * @date 2022/1/21 15:04
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = SharpException.class)
    public ResponseEntity<Void> sharpExceptionHandler(SharpException e, HttpServletRequest request) {
        String uri = request.getRequestURI();
        log.error("请求地址'{}',异常信息'{}'", uri, e.getErrorMessage());
        return ResponseEntity.error(e.getCode(), e.getErrorMessage());
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler({ MethodArgumentNotValidException.class, BindException.class })
    public ResponseEntity<List<String>> methodArgumentNotValidExceptionHandler(Exception e, HttpServletRequest request) {
        String uri = request.getRequestURI();
        log.error("请求地址'{}',异常信息'{}'", uri, e.getMessage());
        List<FieldError> fieldErrors = null;
        if (e instanceof MethodArgumentNotValidException) {
            fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
        }
        if (e instanceof BindException) {
            fieldErrors = ((BindException) e).getBindingResult().getFieldErrors();
        }
        if (fieldErrors == null) {
            return ResponseEntity.error(ResponseStatus.METHOD_ARGUMENT_NOT_VALID.value(), ResponseStatus.METHOD_ARGUMENT_NOT_VALID.getMsg());
        }

        List<String> defaultMessages = new ArrayList<>(fieldErrors.size());
        for (FieldError fieldError : fieldErrors) {
            defaultMessages.add(fieldError.getField() + ":" + fieldError.getDefaultMessage());
        }
        ResponseEntity<List<String>> error = ResponseEntity.error(ResponseStatus.METHOD_ARGUMENT_NOT_VALID.value(), ResponseStatus.METHOD_ARGUMENT_NOT_VALID.getMsg());
        error.setData(defaultMessages);
        return error;
    }


    /**
     * 系统异常
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Void> exceptionHandler(Exception e, HttpServletRequest request) {
        String uri = request.getRequestURI();
        log.error("请求地址'{}',异常信息'{}'", uri, e.getMessage());
        return ResponseEntity.error(ResponseStatus.FAIL.value(), ResponseStatus.FAIL.getMsg());
    }
}
